package com.xwaf.platform.system.provider.config;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import com.xwaf.platform.system.provider.hander.WebSocketNettyChildHandler;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.Channel;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;

/**
 * 
 * <p>
 * webSocket服务器
 * <p>
 * 
 * @author 李聪 <br>
 * @email xwaf_love@yeah.net <br>
 * @since JDK 1.8<br>
 * @date 2020年1月9日 下午12:26:22 <br>
 * @see 无<br>
 *      Copyright (c) 2020, xwaf_love@yeah.net All Rights Reserved.<br>
 */
@Component
public class WebSocketNettyServer {
	private static final Logger LOGGER = LoggerFactory.getLogger(WebSocketNettyServer.class);

	/**
	 * <p>
	 * 启动服务端的方法<br>
	 * 推荐的线程数量计算公式：<br>
	 * 1. 线程数量 = （线程总时间/瓶颈资源时间） * 瓶颈资源的线程并行数 <br>
	 * 2. QPS = 1000/线程总时间 * 线程数
	 * <p>
	 * 
	 * @author 李聪 <br>
	 * @email xwaf_love@yeah.net <br>
	 * @since JDK 1.8<br>
	 * @date 2020年1月9日 下午12:26:33 <br>
	 * @see 无<br>
	 * @param port
	 *            服务器监听的端口号
	 * @param webSocketUrl
	 * @throws Exception
	 * @demo <br>
	 */
	public void run(int port, String webSocketUrl) throws Exception {
		EventLoopGroup bossGroup = new NioEventLoopGroup();
		EventLoopGroup workerGroup = new NioEventLoopGroup();
		try {
			ServerBootstrap bootstrap = new ServerBootstrap();
			bootstrap.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class)
					.childHandler(new WebSocketNettyChildHandler(webSocketUrl));
			Channel ch = bootstrap.bind(port).sync().channel();
			LOGGER.info("├ [服务器启动端口]: {}\n", port);
			ch.closeFuture().sync();
		} finally {
			bossGroup.shutdownGracefully();
			workerGroup.shutdownGracefully();
		}
	}
}
